//
//  ChangeLocalCtrl.m
//  百度地图应用
//
//  Created by Cheng on 16/4/12.
//  Copyright © 2016年 game. All rights reserved.
//

#import "ChangeLocalCtrl.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
//
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件

#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件

#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import "CityModel.h"

#define imageCertY ((self.view.frame.size.height-64-35)/2)

@interface ChangeLocalCtrl ()<BMKMapViewDelegate,BMKGeoCodeSearchDelegate,UIActionSheetDelegate,BMKLocationServiceDelegate>
{

	BMKGeoCodeSearch* _geocodesearch;

    UIView *_hahaView;
    BOOL _isfirst;
    
    NSString *_latitude;//经度
    NSString *_longitute;//纬度
    NSString *_localName;
    NSString *_localCity;
    
    BMKLocationService* _locService;
}
@property (weak, nonatomic) IBOutlet UILabel *showlab;
@property (weak, nonatomic) IBOutlet UIView *footView;
@property (nonatomic,strong) BMKMapView *mapView;
@property (nonnull,strong) UIImageView *imageView;

//@property (nonatomic,strong) uiuser
@end

@implementation ChangeLocalCtrl
- (IBAction)back:(UIButton *)sender {

    NSArray *viewcontrollers=self.navigationController.viewControllers;
    if (viewcontrollers.count>1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {//push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{//present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }

}
- (IBAction)sureClick:(id)sender {
    if (_localCity.length!=0) {
        
        NSDictionary *dic= [Manager WeathcityFromSQl:[_localCity substringToIndex:_localCity.length-1]];
        CityModel *model = [[CityModel alloc]initWithDictionary:dic error:nil];
        if (_ChangeBlobk) {
            _ChangeBlobk(_localName,_latitude,_longitute,model.pinyin,model.code);
        }

    }
    
    NSArray *viewcontrollers=self.navigationController.viewControllers;
    if (viewcontrollers.count>1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {//push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{//present方式
        [self dismissViewControllerAnimated:YES completion:nil];
    }

}

-(void)viewDidLoad{

    [super viewDidLoad];

    self.view.frame = [UIScreen mainScreen].bounds;
    
    BMKMapView* mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:mapView];
    _mapView = mapView;
    [_mapView setZoomLevel:14];
    
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _locService = [[BMKLocationService alloc]init];
    
    [_locService startUserLocationService];//开启定位服务
    
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
    
    NSUserDefaults *Myud = [NSUserDefaults standardUserDefaults];
    CGFloat longitude;
    CGFloat latitude;
    
    if ([Myud valueForKey:@"Locallongitude"]==nil&&[Myud valueForKey:@"Locallatitude"]==nil) {
        
        longitude = [[Myud valueForKey:@"Locallongitude"] floatValue];
        latitude = [[Myud valueForKey:@"Locallatitude"] floatValue];
        
    }else{
    
        longitude = [[Myud valueForKey:@"longitude"] floatValue];
        latitude = [[Myud valueForKey:@"latitude"] floatValue];
    }
    
    
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){latitude, longitude};
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
  [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    
    

    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 35)];
    _imageView.centerX = _mapView.centerX;
    _imageView.centerY = imageCertY;
    _imageView.image = [UIImage imageNamed:@"钓点标注"];
    [_mapView addSubview:_imageView];
    
    
    UIImageView *lab = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 5)];
    
    lab.image = [UIImage imageNamed:@"position_noraml_02~iphone"];
    lab.centerX = _mapView.centerX;
    lab.centerY = imageCertY+25;

    [_mapView addSubview:lab];
    
    [self.view bringSubviewToFront:self.footView];
}

/**
*用户方向更新后，会调用此函数
*@param userLocation 新的用户位置
*/
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    //
    //    NSLog(@"%@--%@",userLocation.title,userLocation.subtitle);
    [_mapView updateLocationData:userLocation];
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

#pragma mark--获取停止移动后的位置  用于传回上一个界面
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        
        self.showlab.text = result.address;
        
        _latitude = [NSString stringWithFormat:@"%f",result.location.latitude];
        _longitute = [NSString stringWithFormat:@"%f",result.location.longitude];
        _localName = result.address;
        _localCity = result.addressDetail.city;
        if (!_isfirst) {
             _mapView.centerCoordinate = result.location;
        }
    }
}




- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{


    [UIView animateWithDuration:0.1 animations:^{
        _imageView.centerY = imageCertY-30;

    }];
    
    
}


-(void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    
    
    self.showlab.text = @"定位中......";
    CLLocationCoordinate2D point = [_mapView convertPoint:_mapView.center toCoordinateFromView:_mapView];
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = point;
    [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    _isfirst = YES;
    
    [UIView animateWithDuration:0.2 animations:^{
        _imageView.centerY = imageCertY;
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [_mapView viewWillAppear];

    _mapView.delegate = self;
    _geocodesearch.delegate = self;
    _locService.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    
    _mapView.delegate = nil; // 不用时，置nil
    _geocodesearch.delegate = nil;
    _locService.delegate = nil;
    
    
}

- (void)dealloc {
    
    
    if (_mapView) {
        _mapView = nil;
    }
}


@end
